package com.agile.leetcode.concurrent.InheritableThreadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * InheritableThreadLocal 的作用以及内存泄漏的原因：可以将父线程的threadlocal传递给子线程。但是当移除父线程的threadlocal，
 * 子线程的threadlocal并不会消失。并且通常来讲子线程是放线程池管理的，不会随着父线程的消失而消失。所以子线程的threadlocal就一直存在，
 * 但是已经用不到了，这就造成了内存泄漏了。
 *
 * @author chenzhangkun
 * @ClassName InheritableThreadLocalSolution
 * @description: TODO
 * @date 2024年09月06日
 */
public class InheritableThreadLocalSolution {
	private static final InheritableThreadLocal<String> inheritableUserNameThreadLocal = new InheritableThreadLocal<>();

	public static void main(String[] args) throws Exception {
		inheritableUserNameThreadLocal.set("czk");
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		executorService.submit(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
				System.out.println(inheritableUserNameThreadLocal.get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		TimeUnit.SECONDS.sleep(1);
		// 移除
		inheritableUserNameThreadLocal.remove();
		// 子线程再获取
		executorService.submit(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
				// 还能获取到
				System.out.println(inheritableUserNameThreadLocal.get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		TimeUnit.SECONDS.sleep(5);
		executorService.shutdown();
	}
}
